<template>
	<div class="recordList">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/' }">
				<i class="lh lh-caiwu fw_100"></i>
			</el-breadcrumb-item>
			<el-breadcrumb-item>账单结算</el-breadcrumb-item>
			<el-breadcrumb-item>人才提现记录</el-breadcrumb-item>
		</el-breadcrumb>

		<div class="content_Box box-shadow">
			<div class="py_5 px_10">
				<el-row>
					<el-col :span="4">
						<el-button
							type="default"
							class="fl"
							@click="downloadOrder()"
							round
							size="mini"
							:disabled="disabledDownloadOrder"
							>导出</el-button
						>
						<el-button type="default" class="fl" @click="downBatchOrder('', selectionOrder, 'all')" round size="mini"
							>批量下载回单</el-button
						>
					</el-col>
					<el-col :span="20" class="fr">
						<el-form :inline="true" class="form-inline fr" @keyup.enter.native="shearchBtn()">
							<el-form-item>
								<el-input v-model="query.sn" placeholder="提现记录编号" class="w_120"></el-input>
							</el-form-item>
							<el-form-item>
								<el-input v-model="query.third_order_sn" placeholder="支付订单号" class="w_120"></el-input>
							</el-form-item>
							<el-form-item>
								<el-input v-model="query.staff_name" placeholder="接单人" class="w_100"></el-input>
							</el-form-item>
							<el-form-item>
								<el-select class="w_180" v-model="query.settlement_channel_sn" placeholder="税源地名称" clearable>
									<el-option
										v-for="(item, index) in selectChannel"
										:key="index"
										:label="item.tax_source"
										:value="item.sn"
									></el-option>
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-select v-model="query.status" placeholder="状态" class="w_120" clearable>
									<el-option
										v-for="(item, index) in statusList"
										:key="index"
										:label="item.label"
										:value="item.value"
									></el-option>
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-select v-model="query.time_type" placeholder="申请时间" class="w_120" clearable>
									<el-option label="申请时间" value="1"></el-option>
									<el-option label="提现成功时间" value="2"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="datetime1">
								<el-date-picker
									size="mini"
									class="w_180i"
									type="datetime"
									value-format="yyyy-MM-dd HH:mm:ss"
									format="yyyy-MM-dd HH:mm:ss"
									default-time="00:00:00"
									placeholder="开始时间"
									v-model="query.start_time"
								></el-date-picker> </el-form-item
							>~
							<el-form-item prop="datetime2">
								<el-date-picker
									size="mini"
									class="w_180i"
									type="datetime"
									value-format="yyyy-MM-dd HH:mm:ss"
									format="yyyy-MM-dd HH:mm:ss"
									default-time="23:59:59"
									placeholder="结束时间"
									v-model="query.end_time"
								></el-date-picker>
							</el-form-item>
							<el-button size="mini" type="primary" class="round-right" native-type="button" @click="shearchBtn"
								>搜索</el-button
							>
							<el-button size="mini" round @click="resetBtn">重置</el-button>
						</el-form>
					</el-col>
				</el-row>
			</div>

			<div class="tableMaxBox">
				<template>
					<!-- 表格部分 -->
					<el-table :data="list" stripe @selection-change="handleSelectionChange">
						<el-table-column type="selection" width="50px" :selectable="checkboxT" disabled="true"> </el-table-column>
						<!-- <el-table-column type="selection" width="50px" disabled="true"> </el-table-column> -->
						<el-table-column prop="sn" label="提现记录编号" width="140"></el-table-column>
						<el-table-column prop="third_order_sn" label="支付订单号" width="180"></el-table-column>
						<el-table-column prop="staff_name" label="接单人" min-width="80">
							<template slot-scope="{ row }">
								<span class="pointer text-primary" @click="toStaffList(row, 1)">{{ row.staff_name }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="mobile" label="接单人电话" min-width="120"></el-table-column>
						<el-table-column label="帐单数量" align="center" min-width="80">
							<template slot-scope="{ row }">
								<span class="pointer text-primary" @click="toStaffList(row, 2)">{{ row.bill_count }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="withdraw_amount" label="提现金额" align="right" min-width="80">
							<template slot-scope="{ row }">
								<span class="text-red">{{ row.withdraw_amount | toFixed }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="rate" label="费率" align="right" min-width="80">
							<template slot-scope="{ row }">
								<span>{{ row.rate | toFixed }} %</span>
							</template>
						</el-table-column>
						<el-table-column prop="expect_amount" label="预计服务费" align="right" min-width="80">
							<template slot-scope="{ row }">
								<span>{{ row.expect_amount | toFixed }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="total_amount" label="总费用" align="right" min-width="80">
							<template slot-scope="{ row }">
								<span>{{ row.total_amount | toFixed }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="bank_card_id" label="银行卡" min-width="180">
							<template slot-scope="{ row }">
								<span>{{ row.bank_card_id | sub_blank }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="bank_name" label="银行名称" min-width="120"></el-table-column>
						<el-table-column prop="tax_source" label="税源地名称" min-width="200"></el-table-column>
						<el-table-column prop="channel_bank_card" label="账号" min-width="170"></el-table-column>
						<el-table-column label="状态" min-width="80">
							<template slot-scope="{ row }">
								<span v-if="row.status != 40" :class="`color-status-${row.status}`">{{ row.statusLabel }}</span>

								<el-tooltip v-else class="item" effect="dark" :content="row.fail_info" placement="top">
									<span :class="`color-status-${row.status}`">{{ row.statusLabel }}</span>
								</el-tooltip>
							</template>
						</el-table-column>
						<el-table-column prop="add_time" label="申请时间" min-width="150"></el-table-column>
						<el-table-column prop="operator" label="操作人" min-width="80"></el-table-column>
						<el-table-column prop="success_time" label="提现成功时间" min-width="150"></el-table-column>
						<el-table-column label="操作" min-width="160px" fixed="right">
							<template slot-scope="{ row }">
								<el-link
									:underline="false"
									type="primary"
									class="InfoFont text-primary"
									@click="downloadOrder(row.bill_detail)"
									>导出明细</el-link
								>
								<el-link
									:underline="false"
									type="primary"
									class="InfoFont text-primary"
									v-if="row.status == 30"
									@click="downBatchOrder(row, row.third_order_sn, 'one')"
									>银行回单</el-link
								>
								<el-link
									:underline="false"
									type="danger"
									class="InfoFont text-primary"
									v-if="row.status == 40"
									@click="restartPay(row)"
									>重新支付</el-link
								>
								<el-link
									:underline="false"
									type="warning"
									class="InfoFont text-primary"
									v-if="row.status == 40"
									@click="changeChannel(row)"
									>修改</el-link
								>
								<el-link
									:underline="false"
									type="success"
									class="InfoFont text-primary"
									v-if="row.status == 40"
									@click="withdrawBtn(row)"
									>手动提现</el-link
								>
							</template>
						</el-table-column>
					</el-table>
					<!-- 分页组件 -->
					<page :total="total" :pageNums="query.page" :disableMountedFetch="true" @pagedata="onChildValue"></page>
				</template>
			</div>
		</div>

		<!-- 修改 -->
		<el-dialog title="修改" :visible.sync="dialogVisible" width="650px" :before-close="handleClose">
			<div>
				<div class="title-key">
					<div class="flex-item">结算通道：</div>
					<div class="flex-item">
						<div
							class="channel-list"
							v-for="(item, index) in selectChannel"
							:key="index"
							:class="item.sn == settlement_channel_sn ? 'channel-active' : ''"
							@click="channelActive(item)"
						>
							<p>{{ item.tax_source }}</p>
							<p>余额：{{ item.balance }}（元）</p>
						</div>
					</div>
				</div>
				<div class="title-key">
					<div class="flex-item">银行卡：</div>
					<div class="flex-item">
						<div
							class="channel-list"
							v-for="(item, index) in bankCardList"
							:key="index"
							:class="item.bank_card_id == settlement_channel_yhk ? 'channel-active' : ''"
							@click="channelActiveYhk(item)"
						>
							<p>{{ item.bank_name }}</p>
							<p>{{ item.bank_card_id }}</p>
						</div>
					</div>
				</div>
				<div class="title-key">
					<div class="flex-item">提现金额：</div>
					<div class="flex-item">{{ activeOrder.withdraw_amount | toFixed }} 元</div>
					<div class="flex-item DX-hint">（ {{ DX_withdraw_amount }} ）</div>
				</div>
				<div class="title-key">
					<div class="flex-item">预计服务费：</div>
					<div class="flex-item">{{ activeOrder.expect_amount | toFixed }} 元</div>
					<div class="flex-item DX-hint">（ {{ DX_expect_amount }} ）</div>
				</div>
				<div class="title-key">
					<div class="flex-item">总费用：</div>
					<div class="flex-item font-bold">{{ activeOrder.total_amount | toFixed }} 元</div>
					<div class="flex-item DX-hint">（ {{ DX_total_amount }} ）</div>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="handleClose()">取 消</el-button>
				<el-button type="primary" @click="submitChannel()">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
var common = require('../../../static/tool.js')
import { fetchgetList, payAgain, artificial, changeChannel, fetchChannelgetList } from '@/api/record.js'
import { bankCardList } from '@/api/staff.js'

import dayjs from 'dayjs'
import axios from 'axios'
export default {
	name: 'ShopMonitoring',
	data() {
		return {
			manageInfo: JSON.parse(sessionStorage.getItem('manageInfo')), //登录信息
			url: common.url,
			head_url: common.head_url,
			dialogVisible: false,
			selectionOrder: [], //选择的订单
			disabledDownloadOrder: false, //是否可以点击批量导出
			query: {
				sn: '',
				third_order_sn: '',
				staff_name: '',
				settlement_channel_sn: '',
				status: '',
				time_type: '1',
				end_time: dayjs().format('YYYY-MM-DD') + ' 23:59:59',
				start_time: dayjs().format('YYYY-MM-DD') + ' 00:00:00',
				page: 1,
				pageSize: 20
			},
			//向分页组件传值
			total: 0,

			list: [],
			selectChannel: [], //选择的结算通道列表
			settlement_channel_sn: '', //选定的结算通道
			settlement_channel_yhk: '', //选定的银行卡
			bank_card_id: '',
			bank_name: '',
			statusList: [
				{ label: '已申请', value: 10 },
				{ label: '提现中', value: 20 },
				{ label: '提现成功', value: 30 },
				{ label: '提现失败', value: 40 }
			],
			//更改结算通道
			activeOrder: '', //选定的订单
			DX_withdraw_amount: 0, //提现金额大写
			DX_expect_amount: 0, //预计服务费
			DX_total_amount: 0, //总金额
			bankCardList: [] //银行卡列表
		}
	},

	created() {},
	mounted() {
		if (this.$route.query.settlement_channel_sn) {
			this.query.settlement_channel_sn = this.$route.query.settlement_channel_sn
		}
		this.fetchgetList()
		this.fetchChannel()
	},
	methods: {
		async fetchgetList() {
			try {
				let ret = await fetchgetList({
					...this.query
				})
				ret.list.forEach(element => {
					element.statusLabel = this.statusList.find(item => item.value == element.status).label
				})
				this.list = ret.list
				this.total = ret.ct
			} catch (error) {
				console.log('error:', error)
			}
		},
		// 	重新支付
		async restartPay(row) {
			try {
				await this.$confirm('确定要重新支付吗, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
				await payAgain({
					sn: row.sn
				})
				this.$message.success('操作成功')
				this.list.forEach(it => {
					if (it.sn === row.sn) it.status = 10
					it.statusLabel = this.statusList.find(item => item.value == it.status).label
				})
			} catch (err) {
				console.log('err', err)
			}
		},

		// 手动提现
		async withdrawBtn(row) {
			try {
				await this.$confirm('确认要手动标记为提现成功吗？, 是否继续?', '提现确认', {
					confirmButtonText: '提交',
					cancelButtonText: '取消',
					type: 'warning'
				})
				await artificial({
					sn: row.sn
				})
				this.$message.success('提现成功')
				this.list.forEach(it => {
					if (it.sn === row.sn) it.status = 30
					it.statusLabel = this.statusList.find(item => item.value == it.status).label
				})
			} catch (err) {
				console.log('err', err)
			}
		},

		// 列表选择框
		handleSelectionChange(val) {
			this.selectionOrder = val.map(x => {
				return {
					sn: x.third_order_sn,
					settlement_channel_type: x.settlement_channel_type
				}
			})
			this.disabledDownloadOrder = this.selectionOrder.length > 0 ? true : false
		},
		// 判断选择框是否禁用
		checkboxT(row) {
			return row.status == 30 ? true : false
		},

		// 导出
		downloadOrder(e) {
			let obj = {}
			if (e) {
				obj.sn = e
				obj.token = sessionStorage.getItem('token')

				var that = this
				axios
					.get(this.url + '/bill/exportBillList', {
						params: obj
					})
					.then(function (response) {
						that.$alert('已添加下载任务，请到下载管理中查看', '', {
							confirmButtonText: '确定'
						})
					})
					.catch(function (error) {
						alert(error)
					})
			} else {
				obj = this.query
				obj.token = sessionStorage.getItem('token')

				let param = $.param(obj)
				window.location.href = this.url + '/withdrawStaff/exportWithdrawStaff?' + param
			}
		},

		// 批量下载回单   / 单个回单
		downBatchOrder(row, sn, type) {
			let that = this
			let settlement_channel_type_sn = ''

			let obj = {}

			if (type == 'all') {
				if (sn.length == 0) {
					return this.$message.error('请选择要下载的回单！')
				}

				//校验选中的settlement_channel_type类型
				let status = false

				let arr = []

				sn.forEach((item, index) => {
					if (item.settlement_channel_type != sn[0].settlement_channel_type) {
						status = true
					}
					settlement_channel_type_sn = item.settlement_channel_type
					arr.push(item.sn)
				})

				if (status == true) {
					return this.$message.error('选择的电子回单类型错误！')
				}

				obj = {
					order_sn: arr.join(',')
				}
			} else {
				const date1 = dayjs(dayjs().format('YYYY-MM-DD HH:mm:ss'))
				let diff = date1.diff(dayjs(row.success_time).format('YYYY-MM-DD HH:mm:ss'), 'day')
				console.log(diff)

				if (diff < 2) return this.$message.error('只能下载前两天之前的电子回单!')

				settlement_channel_type_sn = row.settlement_channel_type
				obj = {
					order_sn: sn
				}
			}

			let param = $.param({ ...obj, token: JSON.parse(sessionStorage.getItem('manageInfo')).token })
			let url = ''
			if (settlement_channel_type_sn == 1) {
				//老逻辑
				if (type == 'one') {
					url = 'https://api.zhongfuyun.com/index.php/openApi/downloadReceipt?' + param
				} else {
					url = 'https://api.zhongfuyun.com/openApi/batchProject?' + param
				}
			} else {
				// 新逻辑
				url = this.url + '/withdrawStaff/downloadReceipt?' + param
			}

			axios
				.get(url)
				.then(function (response) {
					console.log(response)
					if (response.data.code == 200) {
						that.$alert('已添加下载任务，请到下载管理中查看', '', {
							confirmButtonText: '确定'
						})
					} else {
						console.log(response.data.msg)
						return that.$message.error(response.data.msg)
					}
				})
				.catch(function (error) {
					alert(error)
				})
		},

		shearchBtn() {
			// 搜索
			this.query.page = 1
			this.fetchgetList()
		},
		//重置
		resetBtn() {
			this.resetData() //重置请求数据
		},

		resetData() {
			//重置请求数据
			this.query.page = 1
			this.query.sn = ''
			this.query.third_order_sn = ''
			this.query.staff_name = ''
			this.query.settlement_channel_sn = ''
			this.query.status = ''
			this.query.time_type = '1'
			this.query.end_time = dayjs().format('YYYY-MM-DD') + ' 23:59:59'
			this.query.start_time = dayjs().format('YYYY-MM-DD') + ' 00:00:00'
			this.fetchgetList()
		},

		// 修改弹框
		changeChannel(row) {
			console.log(row)
			this.activeOrder = row
			this.settlement_channel_sn = row.settlement_channel_sn
			this.DX_withdraw_amount = this.DX(row.withdraw_amount)
			this.DX_expect_amount = this.DX(row.expect_amount)
			this.DX_total_amount = this.DX(row.total_amount)
			this.dialogVisible = true
			this.userBankCardList(row.staff_sn) //银行卡列表
		},
		handleClose() {
			this.dialogVisible = false
			this.activeOrder = ''
			this.settlement_channel_sn = ''
			this.bank_card_id = ''
			this.bank_name = ''
		},
		channelActive(item) {
			this.settlement_channel_sn = item.sn
		},
		channelActiveYhk(item) {
			this.settlement_channel_yhk = item.bank_card_id
			this.bank_card_id = item.bank_card_id
			this.bank_name = item.bank_name
		},

		async submitChannel() {
			try {
				await changeChannel({
					sn: this.activeOrder.sn,
					settlement_channel_sn: this.settlement_channel_sn,
					bank_card_id: this.bank_card_id,
					bank_name: this.bank_name
				})
				this.$message.success('更换成功')
				this.dialogVisible = false
				this.activeOrder = ''
				this.settlement_channel_sn = ''
				this.fetchgetList()
			} catch (err) {
				console.log(err)
			}
		},
		// 放法获取金额大写
		DX(n) {
			if (n == '') return ''
			if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) return '数据非法'
			var unit = '千百拾亿千百拾万千百拾元角分',
				str = ''
			n += '00'
			var p = n.indexOf('.')
			if (p >= 0) n = n.substring(0, p) + n.substr(p + 1, 2)
			unit = unit.substr(unit.length - n.length)
			for (var i = 0; i < n.length; i++) str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i)
			return str
				.replace(/零(千|百|拾|角)/g, '零')
				.replace(/(零)+/g, '零')
				.replace(/零(万|亿|元)/g, '$1')
				.replace(/(亿)万|壹(拾)/g, '$1$2')
				.replace(/^元零?|零分/g, '')
				.replace(/元$/g, '元整')
		},

		//点击人去 人才帐单
		toStaffList(row, type) {
			// console.log(row)
			let item = {}
			if (type == 1) {
				item.staff_name = row.staff_name
				this.$router.push({
					path: '/personnelList',
					query: item
				})
			}
			if (type == 2) {
				item.withdraw_cash_sn = row.sn
				this.$router.push({
					path: '/staffList',
					query: item
				})
			}
		},
		// 获取结算通道列表
		async fetchChannel() {
			try {
				const res = await fetchChannelgetList({})
				res.list.forEach(it => {
					if (+it.status === 1) {
						this.selectChannel.push(it)
					}
				})
			} catch (err) {
				console.log(err)
			}
		},
		async userBankCardList(staff_sn) {
			try {
				let ret = await bankCardList({ staff_sn: staff_sn })
				this.bankCardList = ret
				// 检测用户的银行卡是否存在于列表中
				// if (ret.filter(x => x.bank_card_id == this.activeOrder.bank_card_id).length > 0) {
				this.settlement_channel_yhk = this.activeOrder.bank_card_id
				this.bank_card_id = this.activeOrder.bank_card_id
				this.bank_name = this.activeOrder.bank_name
				// } else {
				// 	this.settlement_channel_sn = ''
				// 	this.bank_card_id = ''
				// 	this.bank_name = ''
				// }
			} catch (err) {
				console.log('error:', err)
			}
		},
		//分页组件->子组件传值
		onChildValue(item) {
			this.query.page = item[0]
			this.query.pageSize = item[1]
			this.fetchgetList()
		}
	},
	// beforeRouteLeave(to, from, next) {
	// 	console.log(to)
	// 	// console.log(from)
	// 	// console.log(next)
	// 	// 设置下一个路由的 meta
	// 	if (to.path == '/staffList') {
	// 		to.meta.keepAlive = false
	// 	}
	// 	next()
	// },
	filters: {
		toFixed(value) {
			if (!value) return '0.00'
			return value.toFixed(2)
		}
	}
}
</script>

<style scoped>
.title-key {
	display: -webkit-flex;
	display: flex;
}

.flex-item {
	min-width: 100px;
	margin-bottom: 15px;
	color: #222222;
}

.title-key .flex-item:nth-child(1) {
	width: 100px;
	text-align: right;
	margin-right: 10px;
	color: #666666;
}
.DX-hint {
	color: #666666;
}

.channel-list {
	box-sizing: border-box;
	display: inline-block;
	/* width: 220px; */
	height: 100px;
	border: 1px dashed #cccccc;
	border-radius: 6px;
	padding: 15px;
	cursor: pointer;
	margin: 0 20px 15px 0;
}
.channel-list p:nth-child(1) {
	margin-bottom: 10px;
}
.channel-active {
	border: 1px solid #0acf97;
	background: url('@/src/assets/img/tongdaoDuihao.svg') bottom right no-repeat #0acf9719;
	background-size: 30px 30px;
}
.font-bold {
	font-weight: bold;
}
.color-status-10 {
	color: #2c4198;
}
.color-status-40 {
	color: #d9001b;
}
.color-status-30 {
	color: #02a7f0;
}
</style>
<style>
.recordList .el-table th .el-checkbox__input {
	display: block;
}
</style>



// WEBPACK FOOTER //
// src/components/talentSettlement/RecordList.vue